package org.example.datastructure.ch6;

public class Calc {
    TreeNode<Character> root;
    public void create(String str){
        int n = str.length();
        TreeNode<Character> p;
        TreeNode<Character> t = root;
        for(int i=0;i<n;i++){
            t = root;
            char c = str.charAt(i);
            if(c>='0' && c<='9'){
                if(root==null){
                    p = new TreeNode(c);
                    root = p;
                    t = p;
                }else{
                    p = new TreeNode(c);
                    while(t.right!=null){
                        t = t.right;
                    }
                    t.right = p;
                }
            }else{
                if(c=='+'||c=='-'){
                    p = new TreeNode(c);
                    p.left = root;
                    root = p;
                }else{
                    if(root.val=='*'||root.val=='/'){
                        p = new TreeNode(c);
                        p.left = root;
                        root = p;
                    }else if(root.val>='0'&&root.val<='9'){
                        p = new TreeNode(c);
                        p.left = root;
                        root = p;
                    }else{
                        p = new TreeNode(c);
                        p.left = root.right;
                        root.right = p;
                    }
                }
            }
        }
        root.preOrder(root);
        System.out.println();
        root.midOrder(root);
    }

    public int result(){
        return dfs(this.root);
    }
    private int dfs(TreeNode rot){
        char c = (char)rot.val;
        if(c>='0' && c<='9'){
            return (int)(c-'0');
        }
        else if(c=='+'){
            return dfs(rot.left)+dfs(rot.right);
        }
        else if(c=='-'){
            return dfs(rot.left)-dfs(rot.right);
        }
        else if(c=='*'){
            return dfs(rot.left)*dfs(rot.right);
        }
        else if(c=='/'){
            return dfs(rot.left)/dfs(rot.right);
        }
        return 0;

    }
}
